<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\Cache;
use think\Url;
use app\common\controller\Handle;
use app\common\model\LogicOut;
use think\facade\Config;


class ApiTop extends BaseController
{

    protected function initialize()
    {
        // $this->logicout = new LogicOut;
        // parent::initialize();
        // $this->version = $this->getVersion();
        // $this->uwindInfo = $this->userInfo();
        // $this->versionnum = $this->getVersionnumber();
    }
    // 下架过期问卷
    public function endNaire()
    {
        $where = [];
        $where[] = ['endTime', '<', time()];
        $where[] = ['status', '=', 1];
        $this->naire->where($where)->update(['status' => 0]);
        // 删除过期逻辑
        // if (date('H') == 15) {
        //     $whereout = [];
        //     $whereout[] = ['type', '=', 0];
        //     $this->logicout->where($whereout)->delete();
        // }
    }
 
    public function newacc()
    {
        $hand = new Handle();
        $hand->newacc();
    }
    //审核版本控制
    protected function getVersion()
    {
        $params = request()->header();
        if (!isset($params['version'])) {
            return false;
        }
        $v = $ver = $this->me_cache('usdgood', 'mini_ver');
        if ($params['version'] == $v) {
            return true;
        }
        return false;
    }


    //根据用户id获取用户信息20201022添加
    protected function byidinfo($id, $isupdate = false)
    {
        if ($isupdate) {
            $return = model('User')->getOne(['id' => $id], []);
            Cache::store('redis')->set('user' . $id, $return);
            return $return;
        }
        $cacheinfo = Cache::store('redis')->get('user' . $id);
        if ($cacheinfo) {
            return $cacheinfo;
        }
        $return = model('User')->getOne(['id' => $id], []);
        Cache::store('redis')->set('user' . $id, $return);
        return $return;
    }


    //根据token获取用户信息

    /**
     * @param false $isupdate
     * @return array|mixed
     * date 2020/10/29 17:05 修改客户端存储id不存储token
     */
    protected function userInfo($isupdate = false)
    {
        $params = request()->header();
        if ($this->apiVersion()) {
            if (!isset($params['access-token']) || empty($params['access-token'])) {
                return [];
            }
            $id = $params['access-token'];
            $id = substr($id, 5);
            return $this->byidinfo($id, $isupdate);
        }
        if (!isset($params['access-token']) || empty($params['access-token'])) {
            return [];
        }
        $token = $params['access-token'];
        if ($isupdate) {
            $return = model('User')->getOne(['token' => $token], []);
            Cache::store('redis')->set($token, $return);
            return $return;
        }
        $cacheinfo = Cache::store('redis')->get($token);
        if ($cacheinfo) {
            return $cacheinfo;
        }
        $return = model('User')->getOne(['token' => $token], []);
        Cache::store('redis')->set($token, $return);
        return $return;
    }



    /**
     * 清除某一项缓存数据
     */
    protected function RemOne($name)
    {
        return Cache::store('redis')->rm($name);
    }
    /**
     * 清空redis
     * @return [type] [description]
     */
    protected function ClearRedis()
    {
        return Cache::store('redis')->clear();
    }
    /**
     * 设置redis
     * @param string  $name  [description]
     * @param [type]  $value [description]
     * @param integer $time  [description]
     */
    protected function SetRedis(string $name, $value)
    {

        return Cache::store('redis')->set($name, $value);
    }
    /**
     * 获取缓存
     * @param string $name [description]
     */
    protected function GetRedis(string $name)
    {
        return Cache::store('redis')->get($name);
    }
    /**
     * 获取本站配置项 usdgood 命令行查看就是 usd_redisusdgood
     * @param  string $name  配置名称
     * @param  string $param 配置数组中的具体值
     * @return [type]        [description]
     */
    protected function me_cache(string $name, string $param = '')
    {
        $value = Cache::store('redis')->get($name);
        if (!$value) {
            $value = model('set')->GetConf($name);
            if (!$value) {
                return [];
            }
            Cache::store('redis')->set($name, $value);
        }
        if ($param)
            return $value[$param];
        else {
            return $value;
        }
    }

    //获取公众平台access_token
    protected function getopen_token()
    {
        if ($this->GetRedis('open_token_time') > time()) {
            return $this->GetRedis('open_token');
        } else {
            $uwind = config('uwind.usd_wx');
            $appid = $uwind['appid'];
            $appsecret = $uwind['appsecret'];
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            $data = [
                'grant_type' => 'client_credential',
                'appid' => $appid,
                'secret' => $appsecret
            ];
            $res = $this->do_get($url, $data);
            $res = json_decode($res, true);
            $this->SetRedis('open_token_time', time() + 7200);
            $this->SetRedis('open_token', $res['access_token']);
            return $res['access_token'];
        }
    }
    //获取公众平台用户信息
    protected function getopen_user($usercount)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/user/get';
        $data['access_token'] = $this->getopen_token();
        $res = $this->do_get($url, $data);
        $res = json_decode($res, true);
        return $res;

        //10000以内情况
        if ($res['total'] < 10000) {
            $total = $res['total'];
            $times = ceil($total / 100);
            if ($total == $usercount) {
                //不需要查询数据
                return $res;
            } else {
                //查询数据判断openid
                $openids = $res['data']['openid'];

                return $res;
                $status = $this->seopen_user($times, $res['data']['openid']);
            }
        }
    }
    //用户数据处理
    private function seopen_user($times, $arr, $i = 0)
    {
        if ($i < $times) {
            $start = $i * 100;
            $open_list = array_slice($arr, $start, 100);
            $array = [];
            foreach ($open_list as $k => $v) {
                $array[] = ['openid' => $v];
            }
            //发送请求
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=' . $this->getopen_token();
            // $data['access_token'] = $this->getopen_token();
            $data['user_list'] = $array;
            // return $data;
            $data = json_encode($data, true);
            $res = $this->curl_post($url, $data);
            $res = json_decode($res, true);
            //拿到用户unionid和openid   存储进数据库并进行下一次递归查询
            $users = $res['user_info_list'];
            $user_data = [];
            foreach ($users as $v) {
                if ($v['subscribe'] == 1) {
                    $user_data[] = [
                        'openid' => $v['openid'],
                        'unionid' => $v['unionid'],
                        'subscribe' => 1
                    ];
                }
            }
            db('user_open')->insertAll($user_data);
            $i++;
            return $this->seopen_user($times, $arr, $i);
        } else {
            return true;
        }
    }
    //post请求
    private function curl_post($url, $data_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            array(
                'X-AjaxPro-Method:ShowList',
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string)
            )
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    //get请求
    private function do_get($url, $params)
    {
        $url = "{$url}?" . http_build_query($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
